<?php

/**
 * This is the model class for table "{{order}}".
 *
 * The followings are the available columns in table '{{order}}':
 * @property integer $id
 * @property string $articul
 * @property string $user_id
 * @property string $is_adaptate
 * @property string $status
 * @property string $status_comment
 * @property string $vimeo_link
 * @property string $date_status
 * @property string $date_created
 * @property string $date_update
 */
class Order extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Order the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{order}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('articul, user_id, is_adaptate, status, date_status', 'required'),
            array('id', 'numerical', 'integerOnly' => true),
            array('articul, vimeo_link', 'length', 'max' => 255),
            array('user_id, is_adaptate, status', 'length', 'max' => 11),
            array('status_comment, date_created, date_update', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, articul, user_id, is_adaptate, status, status_comment, vimeo_link, date_status, date_created, date_update', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'articul' => 'Articul',
            'user_id' => 'User',
            'is_adaptate' => 'Is Adaptate',
            'status' => 'Status',
            'status_comment' => 'Status Comment',
            'vimeo_link' => 'Vimeo Link',
            'date_status' => 'Date Status',
            'date_created' => 'Date Created',
            'date_update' => 'Date Update',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('articul', $this->articul, true);
        $criteria->compare('user_id', $this->user_id, true);
        $criteria->compare('is_adaptate', $this->is_adaptate, true);
        $criteria->compare('status', $this->status, true);
        $criteria->compare('status_comment', $this->status_comment, true);
        $criteria->compare('vimeo_link', $this->vimeo_link, true);
        $criteria->compare('date_status', $this->date_status, true);
        $criteria->compare('date_created', $this->date_created, true);
        $criteria->compare('date_update', $this->date_update, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            $this->setDateUpdate();
            return true;
        }
		
        return false;
    }
	
	protected function beforeValidate() {
        if (parent::beforeValidate()) {
			if($this->isNewRecord)
			{
				$this->status = 0;
				$this->setDateCreate();
				$this->setDateStatus();
				$this->setDateUpdate();
			}
			
            return true;
        }
		
        return false;
    }
	
    public function beforeCreate() {
	
		 $this->status = 0;
		 $this->setDateCreate();
		 $this->setDateStatus();
		 $this->setDateUpdate();
    }

    public function getStatusString() {
        switch ($this->status) {
            case 0:
                return 'на рассмотрении';
                break;
            case 1:
                return 'Одобрен';
                break;
            case 2:
                return 'Не Одобрен';
                break;
            case 3:
                return 'Оплачен';
                break;
            case 4:
                return 'Сделан';
                break;
			case 5:
                return 'Менеджер посмотри';
                break;
            case 99:
                return 'Закрыт';
                break;
        }
    }

    public function newOrder() {
        $this->status = 0;
        $this->setDateUpdate();
        $this->sendMails();
    }

    public function approve() {
        //0 -> 1
        //2 -> 1
        $this->status = 1;
        $this->setDateUpdate();
        $this->sendMails();
    }

    /**
     * заказ не соответствует нормам
     * @param String $text Текст поясняющий причину отказа
     */
    public function decline($text) {
        $this->status = 2;
        $this->status_comment = $text;
        $this->setDateUpdate();
        $this->sendMails();
        //0 -> 2
        //2 -> 2
    }

    public function pay() {
        $this->status = 3;
        $this->setDateUpdate();
        $this->sendMails();
        //1 -> 3
    }

    public function make($link) {
        $this->status = 4;
        $this->vimeo_link = $link;
        $this->setDateUpdate();
        $this->sendMails();
        //3 -> 4
    }

    public function close() {
        //* -> 99
        $this->status = 99;
        $this->setDateUpdate();
        $this->sendMails();
    }
	
	public function managerSee() {
        //* -> 99
        $this->status = 5;
        $this->setDateUpdate();
        $this->sendMails();
    }

    protected function setDateStatus() {
        $this->date_status = date('Y-m-d H:i:s');
    }

    protected function setDateUpdate() {
        $this->date_update = date('Y-m-d H:i:s');
    }

    protected function setDateCreate() {
        $this->date_created = date('Y-m-d H:i:s');
    }

    public function getStatusId() {
        return $this->status;
    }

    public function getManagerEmail() {
        //@todo
        return 'suvorov.igor.90@gmail.com';
    }

    public function getClientEmail() {
        //@todo
        return 'suvorov.igor.90@gmail.com';
    }

    public function getFileDir() {
        return '/uploads/orders/' . $this->id . '/';
    }

    public function getAbsoluteFileDir() {
        //@todo basePath
        return dirname(YII_PATH) . $this->getFileDir();
    }

    public function getFileName() {
        $files = scandir($this->getAbsoluteFileDir());
        return $files[2];
    }

    public function getFileLink() {
        return 'http://' . $_SERVER['HTTP_HOST'] . '/order' . $this->getFileDir() . $this->getFileName();
    }

    public function getPayLink() {
        //@todo
        return 'http://' . $_SERVER['HTTP_HOST'] . '/order/УТКА';
    }

    public function getOrderLink() {
        //@todo
        return 'http://' . $_SERVER['HTTP_HOST'] . '/order/УТКА';
    }

    public function getVimeoLink() {
        return $this->vimeo_link;
    }

    protected function sendMails() {


        $header = "From: \"Robot Wezze\" <robot@wezze.com>\n";
        $header .= "Content-type: text/plain; charset=\"utf-8\"";





        $subject_filename = dirname(dirname(__FILE__)) . '/views/messages/client_' . $this->getStatusId() . '_subject.php';
        $message_filename = dirname(dirname(__FILE__)) . '/views/messages/client_' . $this->getStatusId() . '_message.php';
        $email = $this->getClientEmail();

        if (is_file($subject_filename) && is_file($message_filename)) {
            ob_start();
            require_once($subject_filename);
            $subject = ob_get_contents();
            ob_end_clean();

            ob_start();
            require_once($message_filename);
            $message = ob_get_contents();
            ob_end_clean();

            mail($email, $subject, $message, $header);
        }






        $subject_filename = dirname(dirname(__FILE__)) . '/views/messages/manager_' . $this->getStatusId() . '_subject.php';
        $message_filename = dirname(dirname(__FILE__)) . '/views/messages/manager_' . $this->getStatusId() . '_message.php';
        $email = $this->getManagerEmail();

        if (is_file($subject_filename) && is_file($message_filename)) {
            ob_start();
            require_once($subject_filename);
            $subject = ob_get_contents();
            ob_end_clean();

            ob_start();
            require_once($message_filename);
            $message = ob_get_contents();
            ob_end_clean();

            mail($email, $subject, $message, $header);
        }
    }

}